#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <memory.h>

#include "Thread.hpp"
#include "Inetaddr.hpp"

using namespace ThreadModule;

uint16_t port;
std::string ip;
int sockfd;

void Send()
{
    struct sockaddr_in peer;
    socklen_t len=sizeof(peer);
    // 初始化清零避免未赋值的字段影响bind
    memset((void *)&peer, 0, len);
    peer.sin_addr.s_addr=inet_addr(ip.c_str());
    peer.sin_port=htons(port);

    while (true)
    {
        std::string input;
        std::cout << "Please Enter#";
        std::getline(std::cin, input);

        sendto(sockfd, input.c_str(), input.size(), 0, (sockaddr *)&peer, len);
    }
}

void Receive()
{
    struct sockaddr_in peer;
    socklen_t len=sizeof(peer);
    while (true)
    {
        char buffer[1024];
        int n = recvfrom(sockfd, buffer, sizeof(buffer), 0, (sockaddr *)&peer, &len);
        if (n > 0)
        {
            buffer[n] = 0;
            std::cout << buffer << std::endl;
        }
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        std::cout << "Usage: ip port";
        exit(1);
    }
    port = std::stoi(argv[2]);
    ip = (char *)argv[1];

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    // client不需要显式bind，避免client端口冲突

    thread send(Send);
    thread recv(Receive);

    send.start();
    recv.start();

    send.join();
    recv.join();

    return 0;
}